/*********************************************************************************
 *FileName:  nsuc16xx_eeprom.c
 *Version:   V1.0
 *Date:      2023-11-29
 ****************************************Includes***********************************/
#include "nsuc16xx_eeprom.h"

/***************************************Variables***********************************/
#define EEPROM_UNLOCK_KEY1 0xfedcba98
#define EEPROM_UNLOCK_KEY2 0x76543210

/***************************************Functions***********************************/

void EEPROM_Unlock(void)
{
    /* unlock sysctrl register */
    SYSCTRL->LKKEYR = SYSCTRL_UNLOCK_KEY;
    /* ENABLE AHB EEPROM CLK */
    SYSCTRL->AHBCGR_b.EPRCEN = 1;
    /* unlock EEPROM */
    EEPROM_CTRL->OKR = EEPROM_UNLOCK_KEY1;
    EEPROM_CTRL->OKR = EEPROM_UNLOCK_KEY2;

    /* config EEPROM */
    EEPROM_CTRL->ECR_b.SBIE = 1;
    EEPROM_CTRL->ECR_b.DBIE = 1;
}

void EEPROM_ErasePage(uint8_t page)
{
    /* Check  Status of SBC */
    while (EEPROM_CTRL->FSR_b.BUSY != 0x00)
        ;
    EEPROM_CTRL->ECR_b.WLA = 1;
    *((uint32_t *)(EEPROMMEM_BASE + 8 * page)) = 0x00;
    *((uint32_t *)(EEPROMMEM_BASE + 8 * page + 4)) = 0x00;
    EEPROM_CTRL->ECR_b.WLA = 0;
    EEPROM_CTRL->ECR_b.ERA = 1;
    /* Check  Status of ERA */
    while (EEPROM_CTRL->ECR_b.ERA != 0x00)
        ;
}

void EEPROM_ProgramPage(uint8_t page, uint32_t *data)
{
    /* Check  Status of SBC */
    while (EEPROM_CTRL->FSR_b.BUSY != 0x00)
        ;
    /* data changed */
    *((uint32_t *)(EEPROMMEM_BASE + 8 * page)) = data[0];
    *((uint32_t *)(EEPROMMEM_BASE + 8 * page + 4)) = data[1];
    /* Check  Status of SBC */
    while (EEPROM_CTRL->FSR_b.BUSY != 0x00)
        ;
}

/***************************************END OF FILE*********************************/
